<!-- eslint-disable vue/no-parsing-error -->
<template>
  <a-modal
    v-model:visible="modalVisible"
    id="content"
    :width="1000"
    @handleCancel="handleCancel"
  >
    <template #title> </template>
    <div>
      <a-form ref="formRef" :model="form.list" auto-label-width>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="roleName" label="条码格式：">
              <a-select v-model="form.list.format" :style="{ width: '320px' }">
                <a-option :value="1">QR二维码</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="条码类型：">
              <a-radio-group :default-checked="2" v-model="form.list.type">
                <a-radio :value="1">物码</a-radio>
                <a-radio :value="2">物料包装码</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="物料编码：">
              <a-input
                mode="button"
                disabled
                v-model="form.list.productNumber"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物料名称：">
              <a-input mode="button" disabled v-model="form.list.productName" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="form.list.type === 1" :gutter="16">
          <a-col :span="12">
            <a-form-item label="规格型号：">
              <a-input mode="button" disabled v-model="form.list.spec" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="基本单位：">
              <a-input mode="button" disabled v-model="form.list.basicName" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="供应商：">
              <a-input
                mode="button"
                disabled
                v-model="form.list.supplierName"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生产日期：" field="manufactureDate" required>
              <a-space>
                <a-date-picker
                  style="width: 200px"
                  v-model="form.list.manufactureDate"
                />
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="form.list.type === 2" :gutter="16">
          <a-col :span="12">
            <a-form-item field="amount" label="包装数量：" required>
              <a-input-number
                :min="1"
                :max="form.list.maxAmount"
                v-model="form.list.amount"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- packages -->
            <a-form-item label="包装单位：">
              <a-space>
                <a-select
                  @change="selectPackages"
                  v-model="form.list.packageUnitId"
                  placeholder="Please select ..."
                >
                  <a-option
                    v-for="item in packages"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-option
                  >
                </a-select>
                <div>换算率</div>
                <a-input-number :min="1" v-model="form.list.conversionRate" />
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="codeAmount" label="条码数量：" required>
              <a-input-number
                :min="1"
                :disabled="!form.list.productId"
                :max="form.list.maxAmount"
                v-model="form.list.codeAmount"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="已使用数量：">
              <div
                ><a-input-number disabled v-model="form.list.usedQuantity"
              /></div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="条码规则：">
              <div>物料编码+生产日期(勾选才显示）+流水号</div>
            </a-form-item>
          </a-col>

          <!-- <a-col :span="12">
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="addBarcode">生成</a-button>
              </a-space>
            </a-form-item>
          </a-col> -->
        </a-row>
      </a-form>
      <!-- <a-table
        v-if="recordData.length"
        :pagination="false"
        :virtual-list-props="{ height: 300 }"
        :scroll="{ x: 950 }"
        :data="recordData"
        @select="onSelect"
        row-key="id"
        :args="args"
        v-model:selectedKeys="selectedKeys"
        :row-selection="rowSelection"
      >
        <template #columns>
          <a-table-column :width="100" title="条码" align="center"
            ><template #cell="{ record }">
              <QRcode
                ref="qrcode"
                :qr-url="`${record.content}`"
                :qr-text="`${record.content}`"
              />
            </template>
          </a-table-column>
          <a-table-column :width="100" title="条码格式" align="center"
            ><template #cell="{ record }">
              {{ record.format === 1 ? 'QR二维码' : '条形码' }}
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="条码类型"
            data-index="name"
            align="center"
            ><template #cell="{ record }">
              {{ record.type === 1 ? '物料条码' : '物料包装条码' }}
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="条码内容"
            data-index="location"
            align="center"
            ><template #cell="{ record }">
              <a-textarea
                v-model="record.content"
                placeholder="Please enter something"
                disabled
                allow-clear
              />
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="启用状态"
            data-index="tier"
            align="center"
            ><template #cell="{ record }">
              <a-typography-text type="success">
                {{ record.state === 1 ? '已启用' : '' }}
              </a-typography-text>
            </template>
          </a-table-column>
        </template>
      </a-table> -->
    </div>
    <template #footer>
      <a-space>
        <a-button @click="modalVisible = false">取消</a-button>
        <a-button type="primary" @click="addBarcode">确定生成</a-button>
      </a-space>
    </template>
  </a-modal>
  <!-- <SelectProduct
    v-model:visible="selectVisible"
    @selectProductEmit="selectProductEmit"
  /> -->
</template>

<script lang="ts" setup>
  import { reactive, computed, ref, watchEffect, onMounted } from 'vue';
  import { postBarcodeAdd } from '@/api/barcode';
  import { getoneMaterial } from '@/api/inventory-management/material-management/index';
  import router from '@/router';
  import { Message } from '@arco-design/web-vue';
  import SelectProduct from './select-product.vue';

  const props = withDefaults(
    defineProps<{
      visible: boolean;
      orderInfo: any;
    }>(),
    {
      visible: false,
    }
  );
  const emit = defineEmits(['update:visible', 'addBarcode']);
  const selectVisible = ref(false);
  const packages = ref([]);
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const selectedKeys = ref([]);
  const form = reactive<any>({
    list: {
      id: undefined,
      supplierId: undefined,
      supplierName: '',
      basicUnitId: undefined,
      productId: undefined,
      productNumber: '',
      format: 1,
      type: 2,
      module: 3,
      manufactureDate: '',
      manufactureDateState: undefined,
      codeAmount: undefined,
      amount: 0,
      productName: undefined,
      spec: '',
      basicName: '',
      maxAmount: undefined,
      managementId: undefined,
      packageUnitId: undefined,
      packageUnitNumber: '',
      conversionRate: undefined,
      barcodeAmount: undefined,
      barcodingAmount: undefined,
    },
  });

  // const copyForm = {
  //   id: undefined,
  //   supplierId: undefined,
  //   supplierName: '',
  //   basicUnitId: undefined,
  //   productId: undefined,
  //   productNumber: '',
  //   format: 1,
  //   type: 1,
  //   module: 2,
  //   manufactureDate: '',
  //   manufactureDateState: undefined,
  //   codeAmount: undefined,
  //   amount: undefined,
  //   productName: undefined,
  //   spec: '',
  //   basicName: '',
  //   maxAmount: undefined,
  //   managementId: undefined,
  //   packageUnitId: undefined,
  //   packageUnitNumber: '',
  //   conversionRate: undefined,
  //   barcodeAmount: undefined,
  //   barcodingAmount: undefined,
  // };

  // 判断用户是否显示弹出框
  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });
  const formRef = ref();
  const rules = reactive({});

  const recordData = ref([]);

  // 取消
  const handleCancel = () => {
    emit('addBarcode', true);
    modalVisible.value = false;
  };

  const goSelectProduct = () => {
    selectVisible.value = true;
  };

  const getData = async () => {
    form.list = {
      id: undefined,
      supplierId: undefined,
      supplierName: '',
      basicUnitId: undefined,
      productId: undefined,
      productNumber: '',
      format: 1,
      type: 2,
      module: 3,
      manufactureDate: '',
      manufactureDateState: undefined,
      codeAmount: undefined,
      amount: undefined,
      productName: undefined,
      spec: '',
      basicName: '',
      maxAmount: undefined,
      managementId: undefined,
      packageUnitId: undefined,
      packageUnitNumber: '',
      conversionRate: undefined,
      barcodeAmount: undefined,
      barcodingAmount: undefined,
    };
    Object.assign(form.list, props.orderInfo);
    form.list.maxAmount = form.list.amount;
    form.list.productNumber = props.orderInfo.managementNumber;
    form.list.productName = props.orderInfo.managementName;
    form.list.productId = props.orderInfo.managementId;
    form.list.amount = 0;
    const res = await getoneMaterial({ id: form.list.productId });
    packages.value = res.packages;
  };
  getData();

  const addBarcode = () => {
    let msg = form.list.codeAmount * form.list.amount;
    formRef.value.validate(async (res: any) => {
      if (!res) {
        if (msg + form.list.usedQuantity > form.list.maxAmount) {
          Message.error('生成条码数量大于可使用数量，无法生成');
          return;
        }
        form.list.manufactureDate = new Date(
          form.list.manufactureDate
        ).toJSON();
        const res = await postBarcodeAdd({ ...form.list });
        recordData.value = res;
        emit('addBarcode', true);
        modalVisible.value = false;
      }
    });
  };

  const selectPackages = (e: number) => {
    const res = JSON.parse(
      JSON.stringify(packages.value.filter((i) => i.id === e) as any)
    );
    form.list.packageUnitId = res[0].id;
    form.list.conversionRate = res[0].conversionRate;
  };

  const selectedIndex: any = ref([]);
  const onSelect = (e: any, id: number, d: any) => {
    const msg: any = recordData.value.findIndex((i: any) => i.id === id);
    if (selectedIndex.value.indexOf(msg) === -1) {
      selectedIndex.value.push(msg);
    } else {
      const res = selectedIndex.value.splice(
        selectedIndex.value.indexOf(msg),
        1
      );
    }
  };

  const BatchDownload = () => {
    let canvas1 = document.getElementById('content');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    selectedIndex.value.forEach((item) => {
      let a = document.createElement('a');
      a.href = canvas[item].toDataURL('img/png');
      a.download = '二维码';
      a.click();
      selectedIndex.value = [];
      selectedKeys.value = [];
    });
  };

  onMounted(() => {
    getData();
  });
</script>

<style scoped lang="less">
  .demo-basic {
    margin-top: 5px;
    width: 500px;
    // margin: auto;
    background-color: aliceblue;
  }
</style>
